//
//  DLNewsFlashView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/17.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLNewsFlashView.h"
#import "DLNewsFlashesListModel.h"

@interface DLNewsFlashView()<UIScrollViewDelegate>

@property(nonatomic, strong)NSTimer *timer;

@property(assign, nonatomic)int titleIndex;

@property(assign, nonatomic)int index;

@property (nonatomic) NSMutableArray *titles;

@property (nonatomic, strong) UILabel *tagLabel;

@property (nonatomic, strong) UIImageView *tagImageView;

@property(nonatomic)UILabel *firstLabel;

@property(nonatomic)UILabel *moreLabel;

@end

@implementation DLNewsFlashView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        self.clipsToBounds = YES;
        kuserManager.homeCurrentSpeakingText = @"";
        [self layoutSubControls];
    }
    return self;
}
- (void) layoutSubControls {
    
    UILabel *tagLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 40, 25)];
    tagLabel.text = @"智讯";
    tagLabel.textAlignment = NSTextAlignmentCenter;
    tagLabel.textColor = kDLBtnNormalBgColor;
    tagLabel.font = [UIFont systemFontOfSize:14];
    tagLabel.layer.borderColor =  kDLBtnNormalBgColor.CGColor;
    tagLabel.layer.borderWidth = 1.0f;
//    [self addSubview:tagLabel];
    self.tagLabel = tagLabel;
    
    UIImageView *imageV = [UIImageView new];
    imageV.frame = CGRectMake(20, 9, 22, 22);
    imageV.image = [UIImage imageNamed:@"machine_natification"];
    [self addSubview:imageV];
    self.tagImageView = imageV;
    
//    [tagLabel resetWidth:0.001];
    
    TTSConfig *instance = [TTSConfig sharedInstance];
    if (instance == nil) {
        return;
    }
    
    //TTS singleton
    if (_iFlySpeechSynthesizer == nil) {
        _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    }
    
    _iFlySpeechSynthesizer.delegate = self;
    
    //set the resource path, only for offline TTS
    NSString *resPath = [[NSBundle mainBundle] resourcePath];
    NSString *newResPath = [[NSString alloc] initWithFormat:@"%@/aisound/common.jet;%@/aisound/xiaoyan.jet",resPath,resPath];
    [[IFlySpeechUtility getUtility] setParameter:@"tts" forKey:[IFlyResourceUtil ENGINE_START]];
    [_iFlySpeechSynthesizer setParameter:newResPath forKey:@"tts_res_path"];
    
    //set speed,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.speed forKey:[IFlySpeechConstant SPEED]];
    
    //set volume,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.volume forKey:[IFlySpeechConstant VOLUME]];
    
    //set pitch,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.pitch forKey:[IFlySpeechConstant PITCH]];
    
    //set sample rate
    [_iFlySpeechSynthesizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
    
    //set TTS speaker
    [_iFlySpeechSynthesizer setParameter:instance.vcnName forKey:[IFlySpeechConstant VOICE_NAME]];
    
    //set text encoding mode
    [_iFlySpeechSynthesizer setParameter:@"unicode" forKey:[IFlySpeechConstant TEXT_ENCODING]];
    
    //set engine type
    [_iFlySpeechSynthesizer setParameter:instance.engineType forKey:[IFlySpeechConstant ENGINE_TYPE]];
    
    NSDictionary* languageDic=@{@"catherine":@"text_english",//English
                                @"xiaoyan":@"text_vietnam",//Vietnamese
                                @"Abha":@"text_hindi",//Hindi
                                @"Gabriela":@"text_spanish",//Spanish
                                @"Allabent":@"text_russian",//Russian
                                @"Mariane":@"text_french"};//French
    
    NSString* textNameKey=[languageDic valueForKey:instance.vcnName];
    NSString* textSample=nil;
    
    if(textNameKey && [textNameKey length]>0){
        textSample=NSLocalizedStringFromTable(textNameKey, @"tts/tts", nil);
    }else{
        textSample=NSLocalizedStringFromTable(@"text_chinese", @"tts/tts", nil);
    }
}

- (void) setSourceArray:(NSArray *)sourceArray {
    _sourceArray = sourceArray;
    
    if (sourceArray.count < 1) {
        return;
    }
    NSMutableArray *mutArr = [NSMutableArray array];
    for (NSInteger i = 0; i < sourceArray.count; i++) {
        DLNewsFlashesListModel *model = sourceArray[i];
        [mutArr addObject:model.content];
    }
    
    NSMutableArray *MutableTitles = [NSMutableArray arrayWithArray:mutArr];
    NSString *str = @"xxxxxxx";
    self.titles = MutableTitles;
    [self.titles addObject:str]; //加一个空的,防止数组为空奔溃
    
    self.index = 1;
    
    UILabel *firstLabel = [UILabel new];
//    self.tagImageView.right
    firstLabel.frame = CGRectMake(self.tagImageView.right + 8, 0, self.width - self.tagImageView.right - 16, self.height);
    firstLabel.font = kSystemFont(14);
    firstLabel.textAlignment = NSTextAlignmentLeft;
    firstLabel.textColor = kDLNormalBlackColor;
    firstLabel.tag = self.index;
    firstLabel.text = self.titles[0];
    [self addSubview:firstLabel];
    firstLabel.userInteractionEnabled = YES;
    self.firstLabel = firstLabel;
    
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(newsLabelTap)];
    [firstLabel addGestureRecognizer:tap1];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:1 block:^(NSTimer * _Nonnull timer) {
        UILabel *fuckLabel = [self viewWithTag:self.index];
        
        UILabel *moreLabel = [UILabel new];
        moreLabel.frame = CGRectMake(self.tagImageView.right + 8, self.height, self.width - self.tagImageView.right - 16, self.height);
        moreLabel.font = kSystemFont(14);
        moreLabel.textAlignment = NSTextAlignmentLeft;
        moreLabel.textColor = kDLNormalBlackColor;
        moreLabel.tag = self.index + 1;
        [self addSubview:moreLabel];
        moreLabel.userInteractionEnabled = YES;
        self.moreLabel = moreLabel;
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(newsLabelTap)];
        [moreLabel addGestureRecognizer:tap2];
        
        //            UILabel *shadowLabel = [UILabel new];
        //            shadowLabel.frame = CGRectMake(moreLabel.width - 50, 0, 50, moreLabel.height);
        //            [moreLabel addSubview:shadowLabel];
        //
        //            CAGradientLayer *gradient = [CAGradientLayer layer];
        //            gradient.frame = CGRectMake(0, 0, shadowLabel.width, shadowLabel.height);
        ////            gradient.colors = [NSArray arrayWithObjects:(id)kColorRGBA(179, 108, 229, 1).CGColor, (id)kColorRGBA(179, 108, 229, 0.5).CGColor,nil];
        //            gradient.colors = [NSArray arrayWithObjects: (id)kColorRGBA(0, 0, 0, 1).CGColor, (id)kColorRGBA(0, 0, 0, 0.1).CGColor,nil];
        //            gradient.startPoint = CGPointMake(1, 0);
        //            gradient.endPoint = CGPointMake(0, 0);
        //            gradient.locations = @[@0.0, @1.0];
        //            [shadowLabel.layer addSublayer:gradient];
        //
        //            UIGraphicsBeginImageContext(gradient.frame.size);
        //            [gradient renderInContext:UIGraphicsGetCurrentContext()];
        //            UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
        //            UIGraphicsEndImageContext();
        //
        //            shadowLabel.backgroundColor = [UIColor colorWithPatternImage:image];
        
        if ([self.titles[self.titleIndex+1] isEqualToString:@"xxxxxxx"]) {
            self.titleIndex = -1;
            self.index = 0;
        }
        
        if (moreLabel.tag == self.titles.count) {
            
            moreLabel.tag = 1;
        }
        
        moreLabel.text = self.titles[self.titleIndex+1];
        
        [self addSubview:moreLabel];
        
        [UIView animateWithDuration:1 animations:^{
            fuckLabel.y = -self.height;
            moreLabel.y = 0;
            
            moreLabel.userInteractionEnabled = NO;
            fuckLabel.userInteractionEnabled = NO;
            
        } completion:^(BOOL finished) {
            
            
            moreLabel.userInteractionEnabled = YES;
            
            fuckLabel.userInteractionEnabled = YES;
            [fuckLabel removeFromSuperview];
        } ];
        self.index++;
        self.titleIndex++;
    }];
    self.timer = timer;
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void) newsLabelTap {
    
    DLNewsFlashesListModel *model = self.sourceArray[self.index - 1];
    NSLog(@"当前展示的是第%d个label, 内容是:%@", self.index - 1, model.content);
    
    
    if (_audioPlayer != nil && _audioPlayer.isPlaying == YES) {
        [_audioPlayer stop];
    }
    
    if ([model.content isEqualToString:kuserManager.homeCurrentSpeakingText] && self.iFlySpeechSynthesizer.isSpeaking == YES) {
        NSLog(@"当前播放的和现在点击的是同一条消息，停止播放");
        NSLog(@"前--------%d", self.iFlySpeechSynthesizer.isSpeaking);
        [self.iFlySpeechSynthesizer stopSpeaking];
        
        
        
        [_audioPlayer stop];
        kuserManager.homeCurrentSpeakingText = @"";
        _state = NotStart;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"后--------%d", self.iFlySpeechSynthesizer.isSpeaking);
        });
        
        //滚动
        [self.timer setFireDate:[NSDate distantPast]];
        
        return;
    } else {
        NSLog(@"当前播放的和现在点击的不是同一条消息，停止播放当前播放的，播放刚才点击的");
        kuserManager.homeCurrentSpeakingText = model.content;
    }
    
    [self.timer setFireDate:[NSDate distantFuture]];
    
    _synType = NomalType;
    
    self.hasError = NO;
    [NSThread sleepForTimeInterval:0.05];
    self.isCanceled = NO;
    
    _iFlySpeechSynthesizer.delegate = self;
    
    NSString *str= model.content;
    NSLog(@"播放的语音对应的文字是：%@", str);
    [_iFlySpeechSynthesizer startSpeaking:str];
    if (_iFlySpeechSynthesizer.isSpeaking) {
        _state = Playing;
    }
}

//结束回调
- (void)onCompleted:(IFlySpeechError *)error {
    NSLog(@"结束回调");
    [self.timer setFireDate:[NSDate distantPast]];
}
// 开始合成回调
- (void) onSpeakBegin {
    NSLog(@"开始合成回调");
    //在这调就晚了，点击的时候就调
//    [self.timer setFireDate:[NSDate distantFuture]];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */


@end
